package org.shoukaiseki.test.corssorigin.demo3;

import org.shoukaiseki.test.business.user.model.SysUser;
import org.shoukaiseki.test.token.Anon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CorssInterceptor3 implements HandlerInterceptor {

    Logger logger= LoggerFactory.getLogger(CorssInterceptor3.class);

    @Value("${hkedou.corss.allowedorigins}")
    String[] allowedorigins;

    /**
     * 返回true才能往下执行，返回false取消当前请求
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        logger.debug("---------------preHandle.url="+request.getServletPath());
        //方式一 start

        //方式一 end
//        response.setHeader("Access-Header", "true");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        for (String origin:allowedorigins ) {
//            response.setHeader("Access-Control-Allow-Origin", origin);
//            response.setHeader("allowedOrigins", origin);
//        }
//        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Headers, Access-Control-Request-Method, Cache-Control, Pragma, Expires");
//        response.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//        response.setHeader("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
//        response.setHeader("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");


        if( request.getSession().getAttribute("sysUser")!=null){
            SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
                return true;
        }

        if(handler instanceof HandlerMethod){
            if(((HandlerMethod) handler).hasMethodAnnotation(Anon.class)){
                return true;
            }else{

            }
        }

        response.sendRedirect("/nologintips");
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

        logger.debug("-----------------{}","postHandle");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.debug("-----------------{}","afterCompletion");

    }
}
